package cn.studyjams.s1.contest.autohello;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.AppCompatSpinner;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import cn.studyjams.s1.contest.autohello.model.RepeatMode;


/**
 * A simple {@link Fragment} subclass.
 */
public class SetRepeatFragment extends DialogFragment implements AdapterView.OnItemSelectedListener, View.OnClickListener, DatePickerDialog.OnDateSetListener {

    private final static String TAG = "SetRepeatFragment";

    AppCompatSpinner repeatTypeSP;
    AppCompatSpinner endConditionSP;

    TextView doesNotRepeatContent;
    LinearLayout repeatEverydayContent;
    LinearLayout repeatEveryweekContent;
    LinearLayout repeatEverymonthContent;
    LinearLayout repeatEveryyearContent;
    LinearLayout endConditionContent;

    EditText everydayET;
    EditText everyweekET;
    EditText everymonthET;
    EditText everyyearET;

    TextView endCondition0;
    Button endCondition1;
    EditText endCondition2;
    TextView endCondition2Quantifier;

    AppCompatCheckBox sunCB, monCB, tueCB, wedCB, thuCB, friCB, satCB;

    RadioGroup sameDayOrsameWeekRG;
    int repeatType;
    //    int howOften;
    int endCondition;
    String mYear, mMonth, mDay;
    //    int endCounts;
    List<Boolean> whichWeeks = new ArrayList<>();
    // int sameDayOrSameWeekOfTheMonth;

    SetRepeatListener setRepeatListener;

    public interface SetRepeatListener {
        void onConfirmSetRepeat(RepeatMode repeatMode);
    }

    public SetRepeatFragment() {
        // Required empty public constructor
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow()
                    .setLayout((int) (dm.widthPixels * 0.85), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            setRepeatListener = (SetRepeatListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + "must implement SetRepeatFragment");
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_set_repeatmode, null);
//        String tag = getArguments().getString("tag");
//
//        final EditText tagET = (EditText) view.findViewById(R.id.tag);
//        tagET.setText(tag);
//        tagET.setSelection(tagET.getText().length());
        repeatTypeSP = (AppCompatSpinner) view.findViewById(R.id.repeat_type);
        endConditionSP = (AppCompatSpinner) view.findViewById(R.id.end_condition);

        doesNotRepeatContent = (TextView) view.findViewById(R.id.does_not_repeat_content);
        repeatEverydayContent = (LinearLayout) view.findViewById(R.id.repeat_everyday_content);
        repeatEveryweekContent = (LinearLayout) view.findViewById(R.id.repeat_everyweek_content);
        repeatEverymonthContent = (LinearLayout) view.findViewById(R.id.repeat_everymonth_content);
        repeatEveryyearContent = (LinearLayout) view.findViewById(R.id.repeat_everyyear_content);
        endConditionContent = (LinearLayout) view.findViewById(R.id.end_condition_content);

        everydayET = (EditText) view.findViewById(R.id.every_day);
        everymonthET = (EditText) view.findViewById(R.id.every_month);
        everyweekET = (EditText) view.findViewById(R.id.every_week);
        everyyearET = (EditText) view.findViewById(R.id.every_year);

        everydayET.setText("1");
        everymonthET.setText("1");
        everyweekET.setText("1");
        everyyearET.setText("1");

        sunCB = (AppCompatCheckBox) view.findViewById(R.id.sunCB);
        monCB = (AppCompatCheckBox) view.findViewById(R.id.monCB);
        tueCB = (AppCompatCheckBox) view.findViewById(R.id.tueCB);
        wedCB = (AppCompatCheckBox) view.findViewById(R.id.wedCB);
        thuCB = (AppCompatCheckBox) view.findViewById(R.id.thuCB);
        friCB = (AppCompatCheckBox) view.findViewById(R.id.friCB);
        satCB = (AppCompatCheckBox) view.findViewById(R.id.satCB);

        sameDayOrsameWeekRG = (RadioGroup) view.findViewById(R.id.same_day_or_same_week_RG);

        endCondition0 = (TextView) view.findViewById(R.id.end_condition_0);
        endCondition1 = (Button) view.findViewById(R.id.end_condition_1);
        endCondition2 = (EditText) view.findViewById(R.id.end_condition_2);
        endCondition2Quantifier = (TextView) view.findViewById(R.id.end_condition_2_quantifier);

        repeatTypeSP.setOnItemSelectedListener(this);
        endConditionSP.setOnItemSelectedListener(this);
        endCondition1.setOnClickListener(this);
        view.findViewById(R.id.set_repeat_mode_btn).setOnClickListener(this);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view);

        return builder.create();
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        AppCompatSpinner spinner = (AppCompatSpinner) adapterView;
        if (spinner.getId() == R.id.repeat_type) {
            switch (i) {
                case 0:
                    repeatType = 0;
                    doesNotRepeatContent.setVisibility(View.VISIBLE);
                    repeatEverydayContent.setVisibility(View.GONE);
                    repeatEveryweekContent.setVisibility(View.GONE);
                    repeatEverymonthContent.setVisibility(View.GONE);
                    repeatEveryyearContent.setVisibility(View.GONE);
                    endConditionContent.setVisibility(View.GONE);
                    break;
                case 1:
                    // repeat every day
                    repeatType = 1;
                    doesNotRepeatContent.setVisibility(View.GONE);
                    repeatEverydayContent.setVisibility(View.VISIBLE);
                    repeatEveryweekContent.setVisibility(View.GONE);
                    repeatEverymonthContent.setVisibility(View.GONE);
                    repeatEveryyearContent.setVisibility(View.GONE);
                    endConditionContent.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    repeatType = 2;
                    doesNotRepeatContent.setVisibility(View.GONE);
                    repeatEverydayContent.setVisibility(View.GONE);
                    repeatEveryweekContent.setVisibility(View.VISIBLE);
                    repeatEverymonthContent.setVisibility(View.GONE);
                    repeatEveryyearContent.setVisibility(View.GONE);
                    endConditionContent.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    repeatType = 3;
                    doesNotRepeatContent.setVisibility(View.GONE);
                    repeatEverydayContent.setVisibility(View.GONE);
                    repeatEveryweekContent.setVisibility(View.GONE);
                    repeatEverymonthContent.setVisibility(View.VISIBLE);
                    repeatEveryyearContent.setVisibility(View.GONE);
                    endConditionContent.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    repeatType = 4;
                    doesNotRepeatContent.setVisibility(View.GONE);
                    repeatEverydayContent.setVisibility(View.GONE);
                    repeatEveryweekContent.setVisibility(View.GONE);
                    repeatEverymonthContent.setVisibility(View.GONE);
                    repeatEveryyearContent.setVisibility(View.VISIBLE);
                    endConditionContent.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
        }

        if (spinner.getId() == R.id.end_condition) {
            switch (i) {
                case 0:
                    endCondition = 0;
                    endCondition0.setVisibility(View.VISIBLE);
                    endCondition1.setVisibility(View.GONE);
                    endCondition2.setVisibility(View.GONE);
                    endCondition2Quantifier.setVisibility(View.GONE);
                    break;
                case 1:
                    endCondition = 1;
                    endCondition0.setVisibility(View.GONE);
                    endCondition1.setVisibility(View.VISIBLE);
                    endCondition2.setVisibility(View.GONE);
                    endCondition2Quantifier.setVisibility(View.GONE);
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
                    mYear = new SimpleDateFormat("yyyy", Locale.getDefault()).format(calendar.getTime());
                    mMonth = new SimpleDateFormat("MM", Locale.getDefault()).format(calendar.getTime());
                    mDay = new SimpleDateFormat("dd", Locale.getDefault()).format(calendar.getTime());
                    String str = String.format(getString(R.string.end_condition_date_picker), mMonth, mDay, mYear);
                    endCondition1.setText(str);
                    break;
                case 2:
                    endCondition = 2;
                    endCondition0.setVisibility(View.GONE);
                    endCondition1.setVisibility(View.GONE);
                    endCondition2.setVisibility(View.VISIBLE);
                    endCondition2Quantifier.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
        Snackbar.make(adapterView, "NothingSelected", Snackbar.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.end_condition_1) {
            DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(
                    this,
                    Integer.parseInt(mYear),
                    Integer.parseInt(mMonth) - 1,
                    Integer.parseInt(mDay)
            );
            datePickerDialog.setVersion(DatePickerDialog.Version.VERSION_2);
            datePickerDialog.show(getActivity().getFragmentManager(), "DATE_PICKER");
        }

        if (view.getId() == R.id.set_repeat_mode_btn) {

            RepeatMode repeatMode = new RepeatMode();

            String howOftenStr;

            switch (repeatType) {
                case 0:
                    // 不重复
                    repeatMode.setRepeatType(0);
                    break;
                case 1:
                    // 每天重复
                    repeatMode.setRepeatType(1);
                    howOftenStr = everydayET.getText().toString();
                    if (TextUtils.isEmpty(howOftenStr)) {
                        everydayET.setError(getString(R.string.required));
                        return;
                    }
                    repeatMode.setHowOften(Integer.parseInt(howOftenStr));
                    repeatMode.setEndCondition(endCondition);
                    if (endCondition == 1) {
                        repeatMode.setEndDateTime(mYear + "-" + mMonth + "-" + mDay);
                    } else if (endCondition == 2) {
                        String endCountsStr = endCondition2.getText().toString();
                        if (TextUtils.isEmpty(endCountsStr)) {
                            endCondition2.setError(getString(R.string.required));
                            return;
                        }
                        repeatMode.setEndCounts(Integer.parseInt(endCountsStr));
                    }
                    break;
                case 2:
                    // 每周重复
                    repeatMode.setRepeatType(2);
                    howOftenStr = everydayET.getText().toString();
                    if (TextUtils.isEmpty(howOftenStr)) {
                        everydayET.setError(getString(R.string.required));
                        return;
                    }
                    repeatMode.setHowOften(Integer.parseInt(howOftenStr));
                    repeatMode.setEndCondition(endCondition);
                    if (endCondition == 1) {
                        repeatMode.setEndDateTime(mYear + "-" + mMonth + "-" + mDay);
                    } else if (endCondition == 2) {
                        String endCountsStr = endCondition2.getText().toString();
                        if (TextUtils.isEmpty(endCountsStr)) {
                            endCondition2.setError(getString(R.string.required));
                            return;
                        }
                        repeatMode.setEndCounts(Integer.parseInt(endCountsStr));
                    }

                    whichWeeks.add(sunCB.isChecked());
                    whichWeeks.add(monCB.isChecked());
                    whichWeeks.add(tueCB.isChecked());
                    whichWeeks.add(wedCB.isChecked());
                    whichWeeks.add(thuCB.isChecked());
                    whichWeeks.add(friCB.isChecked());
                    whichWeeks.add(satCB.isChecked());

                    Boolean flag = false;
                    for (Boolean check : whichWeeks) {
                        flag |= check;
                    }

                    if (flag) {
                        repeatMode.setWhichWeeks(whichWeeks.toString());
                        Log.d(TAG, whichWeeks.toString());
                    } else {
                        Snackbar.make(view, getString(R.string.week_limit), Snackbar.LENGTH_LONG)
                                .show();
                        return;
                    }
                    break;
                case 3:
                    // 每月重复
                    repeatMode.setRepeatType(3);
                    howOftenStr = everydayET.getText().toString();
                    if (TextUtils.isEmpty(howOftenStr)) {
                        everydayET.setError(getString(R.string.required));
                        return;
                    }
                    repeatMode.setHowOften(Integer.parseInt(howOftenStr));
                    repeatMode.setEndCondition(endCondition);
                    if (endCondition == 1) {
                        repeatMode.setEndDateTime(mYear + "-" + mMonth + "-" + mDay);
                    } else if (endCondition == 2) {
                        String endCountsStr = endCondition2.getText().toString();
                        if (TextUtils.isEmpty(endCountsStr)) {
                            endCondition2.setError(getString(R.string.required));
                            return;
                        }
                        repeatMode.setEndCounts(Integer.parseInt(endCountsStr));
                    }

                    int radioButtonID = sameDayOrsameWeekRG.getCheckedRadioButtonId();
                    View radioButton = sameDayOrsameWeekRG.findViewById(radioButtonID);
                    int idx = sameDayOrsameWeekRG.indexOfChild(radioButton);
                    repeatMode.setSameDayOrSameWeekOfTheMonth(idx);

                    Log.d(TAG, idx + "");
                    break;
                case 4:
                    // 每年重复
                    repeatMode.setRepeatType(4);
                    howOftenStr = everydayET.getText().toString();
                    if (TextUtils.isEmpty(howOftenStr)) {
                        everydayET.setError(getString(R.string.required));
                        return;
                    }
                    repeatMode.setHowOften(Integer.parseInt(howOftenStr));
                    repeatMode.setEndCondition(endCondition);
                    if (endCondition == 1) {
                        repeatMode.setEndDateTime(mYear + "-" + mMonth + "-" + mDay);
                    } else if (endCondition == 2) {
                        String endCountsStr = endCondition2.getText().toString();
                        if (TextUtils.isEmpty(endCountsStr)) {
                            endCondition2.setError(getString(R.string.required));
                            return;
                        }
                        repeatMode.setEndCounts(Integer.parseInt(endCountsStr));
                    }
            }

            SetRepeatListener listener = (SetRepeatListener) getActivity();
            listener.onConfirmSetRepeat(repeatMode);
            dismiss();
        }
    }

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        mYear = year + "";
        mMonth = (monthOfYear + 1) + "";
        mDay = dayOfMonth + "";
        String str = String.format(getString(R.string.end_condition_date_picker), mMonth, mDay, mYear);
        endCondition1.setText(str);
    }
}
